<?php
/*
 * This class is used to parse the tweets downloaded from twitter in order to 
 * find links to youtube's videos.
 */

class Parser
{
  public $tweet;
  public $splitted_tweet;
  public $link;

  public static $youtube_link='www.youtube.com/';
  public static $youtube_link2='http://www.youtube.com/';

  // construct the Parser object
  public function __construct ($message)
  {
    $this->tweet = $message;
    $this->splitted_tweet= array();
    $this->link=NULL;
  } 

  // split the message in an array of words
  public function split_message ()
  {
    $this->tweet=str_replace("\n", " ", $this->tweet);
    $this->splitted_tweet=explode(" ",$this->tweet);
  }

  // search for a youtube's videos and if it finds it return the link, false otherwise.
  public function search_for_video ()
  {
    $videos=array(); //contains all the links to youtube videos
    foreach($this->splitted_tweet as $word)
      {
	//check if it is a complete url
	$pos= strpos($word, self::$youtube_link);
	if($pos === false)
	  {
	    //check if it is a shortern url
	    if(strpos($word, "http:")!==false ||  strpos($word, "www.")!==false)
	      {
		$long_url=file_get_contents("http://api.longurl.org/v2/expand?url=".$word."&format=json");
		$Jresponse = json_decode($long_url, true);
		$url = $Jresponse['long-url'];
		if($url != "Could not expand URL. Please check that you have submitted a valid URL.")
		  if(strpos($url, self::$youtube_link)!==false || strpos($url, self::$youtube_link2)!==false)
		    $videos[]=$url;
	      }
	  }
	else
	  $videos[]=$word;
	
      }
    return $videos;
  }
}
?>